﻿//
// Copyright (c) 2010
// by Chris Paterra
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System.ComponentModel;
using System.Linq;
using System;
using System.Web.UI.WebControls;
using DotNetNuke.ContentLibrary.Components.Common;
using DotNetNuke.ContentLibrary.Components.Controllers;
using DotNetNuke.ContentLibrary.Components.Entities;
using Telerik.Web.UI;

namespace DotNetNuke.ContentLibrary.Components.WebControls 
{

	/// <summary>
	/// The UserRating control is meant to show a specific user's applied rating for a contentitem/childtype/childkeyid combination. The user is allowed to add or update their existing rating using this control. Please keep in mind, this is not meant for an overall rating to display to end users.
	/// </summary>
	public class UserRating : ControlBase
	{

		public event EventHandler RatingClick;
		public event EventHandler VoteClick;

		#region Private Members

		private string _skin = "Default";
		private string _thumbsUpImage = "~/DesktopModules/ContentLibrary/images/up.png";
		private string _thumbsUpImageHover = "~/DesktopModules/ContentLibrary/images/uph.png";
		private string _thumbsUpImageSelected = "~/DesktopModules/ContentLibrary/images/ups.png";
		private string _thumbsDownImage = "~/DesktopModules/ContentLibrary/images/down.png";
		private string _thumbsDownImageHover = "~/DesktopModules/ContentLibrary/images/downh.png";
		private string _thumbsDownImageSelected = "~/DesktopModules/ContentLibrary/images/downs.png";
		private static readonly object EventSubmitKey = new object();

		private DnnRating _ratingControl;
		private LinkButton _voteYes;
		private LinkButton _voteNo;

		private ControlBehavior.RatingControlMode _ratingMode = ControlBehavior.RatingControlMode.Stars;

		private int ChildTypeID()
		{
				if (ChildType == "") {
					return 0;
				}

				// query child types
				var cntController = new ContentLibraryController();
				var objChildType = (from t in cntController.GetChildTypes() where (t.ChildType == ChildType) select t).SingleOrDefault();
				if (objChildType != null) {
					return objChildType.ChildTypeID;
				}

				// create the child type
				var objType = new ChildTypeInfo { ChildType = ChildType, CreatedOnDate = DateTime.Now };
				return cntController.AddChildType(objType);
		}

		#endregion

		#region Public Properties

		public int ChildKeyID {
			get {
				var childKeyID = 0;
				if (ViewState["ChildKeyID"] != null) {
					childKeyID = Convert.ToInt32(ViewState["ChildKeyID"]);
				}
				return childKeyID;
			}
			set { ViewState["ChildKeyID"] = value; }
		}

		public string ChildType {
			get {
				var childType = "";
				if (ViewState["ChildType"] != null) {
					childType = Convert.ToString(ViewState["ChildType"]);
				}
				return childType;
			}
			set { ViewState["ChildType"] = value; }
		}

		public ControlBehavior.RatingControlMode RatingMode
		{
			get { return _ratingMode; }
			set { _ratingMode = value; }
		}

		/// <summary>
		/// Right now i don't see a reason this needs to be available outside of this class. ReadOnly is used when displaying a specific user's rating (for an item), which I think we only need to do with controls within this suite (ie. reviews list control). 
		/// </summary>
		internal bool IsReadOnly { get; set; }

		public string ThumbsUpImage {
			get { return _thumbsUpImage; }
			set { _thumbsUpImage = value; }
		}

		public string ThumbsUpImageHover {
			get { return _thumbsUpImageHover; }
			set { _thumbsUpImageHover = value; }
		}

		public string ThumbsUpImageSelected {
			get { return _thumbsUpImageSelected; }
			set { _thumbsUpImageSelected = value; }
		}

		public string ThumbsDownImage {
			get { return _thumbsDownImage; }
			set { _thumbsDownImage = value; }
		}

		public string ThumbsDownImageHover {
			get { return _thumbsDownImageHover; }
			set { _thumbsDownImageHover = value; }
		}

		public string ThumbsDownImageSelected {
			get { return _thumbsDownImageSelected; }
			set { _thumbsDownImageSelected = value; }
		}

		public string Skin {
			get { return _skin; }
			set { _skin = value; }
		}

		#endregion

		#region Private Methods

		/// <summary>
		/// This method either creates a user rating for the specified item or it will update an existing one with a new value (and modified data). 
		/// </summary>
		private void UpdateUserRating(decimal ratingValue) {
			var cntController = new ContentLibraryController();
			var currentChildTypeID = ChildTypeID();

			cntController.UpdateUserRating(ratingValue, CurrentContentItemID, ChildKeyID, currentChildTypeID, CurrentUserID, DateTime.Now);
		}

		#endregion

		#region Public Methods

		protected override void CreateChildControls() {
			base.CreateChildControls();

			Controls.Clear();

			switch (RatingMode)
			{
				case ControlBehavior.RatingControlMode.Thumbs:
					_ratingControl = new DnnRating { ID = String.Concat(ID, "_Rating"), AutoPostBack = true, ItemWidth = 32, ItemHeight = 32 };
					_ratingControl.Rate += OnRatingClick;
					_ratingControl.SelectionMode = RatingSelectionMode.Single;
					_ratingControl.Precision = RatingPrecision.Item;

					Controls.Add(_ratingControl);
					break;
				case ControlBehavior.RatingControlMode.YesNo:
					_voteYes = new LinkButton { ID = String.Concat(ID, "_YesBtn"), Text = "Yes", CommandArgument = "1", CssClass="CommandButton" };
					_voteYes.Command += VoteCommand;
					Controls.Add(_voteYes);

					_voteNo = new LinkButton { ID = String.Concat(ID, "_NoBtn"), Text = "No", CommandArgument = "-1", CssClass = "CommandButton" };
					_voteNo.Command += VoteCommand;
					Controls.Add(_voteNo);
					break;
				default:
					_ratingControl = new DnnRating { ID = String.Concat(ID, "_Rating"), AutoPostBack = true};
					_ratingControl.Rate += OnRatingClick;
					_ratingControl.SelectionMode = RatingSelectionMode.Continuous;
					_ratingControl.Precision = RatingPrecision.Item;

					Controls.Add(_ratingControl);
					break;
			}
		}

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			EnsureChildControls();
		}

		protected override void OnPreRender(EventArgs e) {
			base.OnPreRender(e);

			switch (RatingMode) {
				case ControlBehavior.RatingControlMode.Thumbs:
					_ratingControl.Enabled = !IsReadOnly && CurrentUserID > 0;
					_ratingControl.ItemCount = 2;
					_ratingControl.Items.Clear();

					var thumbsDn = new RadRatingItem(ResolveUrl(ThumbsDownImage), ResolveUrl(ThumbsDownImageSelected), ResolveUrl(ThumbsDownImageHover))
					               	{
					               		Value = 0,
										ToolTip = Services.Localization.Localization.GetString("ThumbsDown", SharedResourceFile)
					               	};

					var thumbsUp = new RadRatingItem(ResolveUrl(ThumbsUpImage), ResolveUrl(ThumbsUpImageSelected), ResolveUrl(ThumbsUpImageHover))
					               	{
					               		Value = 1,
										ToolTip = Services.Localization.Localization.GetString("ThumbsUp", SharedResourceFile)
					               	};

					_ratingControl.Items.Add(thumbsDn);
					_ratingControl.Items.Add(thumbsUp);
					break;
				case ControlBehavior.RatingControlMode.YesNo:
					_voteYes.Enabled = !IsReadOnly && CurrentUserID > 0;
					_voteNo.Enabled = !IsReadOnly && CurrentUserID > 0;
					break;
				default:
					_ratingControl.Enabled = !IsReadOnly && CurrentUserID > 0;
					_ratingControl.Skin = Skin;
					break;
			}

			// here is where we apply the current user's rating
			if (CurrentUserID <= 0) return;
			var cntController = new ContentLibraryController();
			var currentChildTypeID = ChildTypeID();

			var objUserRating = (from t in cntController.GetUserRatings(CurrentUserID, PortalID) where (t.ContentItemID == CurrentContentItemID) & (t.ChildKeyID == ChildKeyID) & (t.ChildTypeID == currentChildTypeID) select t).SingleOrDefault();

			if (objUserRating == null) return;
			switch (RatingMode)
			{
				case ControlBehavior.RatingControlMode.YesNo:
					if (objUserRating.Value == -1)
					{
						_voteNo.Enabled = false;
					}
					else
					{
						if (objUserRating.Value == 1)
						{
							_voteYes.Enabled = false;
						}
					}
					break;
				default:
					_ratingControl.Value = objUserRating.Value;
					break;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void OnRatingClick(object sender, EventArgs e) {
			if (RatingClick != null) {
				RatingClick(this, e);
			}

			UpdateUserRating(_ratingControl.Value);
		}

		/// <summary>
		/// The Vote event.
		/// </summary>
		/// <remarks>This is normally done behind the scenes by .net, implemented here for performance reasons.</remarks>
		[Category("Action"),
		Description("Raised when the user clicks one of the vote buttons/images.")]
		public event EventHandler Vote {
			add {
				Events.AddHandler(EventSubmitKey, value);
			}
			remove {
				Events.RemoveHandler(EventSubmitKey, value);
			}
		}

		protected void VoteCommand(object sender, CommandEventArgs e) {
			//Raise the VoteClick Event
			if (VoteClick != null) {
				VoteClick(this, e);
			}

			UpdateUserRating(Convert.ToDecimal(e.CommandArgument));
		}

		#endregion

	}
}